import React, { useRef, useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Form, Button, Input, Space, Tabs, Select, Switch, Table, Collapse, Radio, message } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'
import { history } from 'umi';
import trans from '@/utils/translate';
import InfoTitle from '@/components/InfoShow/InfoTitle'
import { FORM_LAYOUT } from '@/utils/const';
import {
  getPublicImage,
  getInference,
  getNodes,
  addInference,
} from './service';
import { inference } from '../const';
import SelectModel, { model} from './components/SelectModel';
import AdvancedConfiguration from './components/AdvanceConfiguration';
import PortMapping from './components/PortMapping';
import SelectNode from './components/SelectNode';
import SelectImage from './components/SelectImage';
import AddEnv, { env } from './components/AddEnv';
import { nameRule } from '@/utils/rule';

const { Item } = Form;

interface image {
  id: string,
  imageName: string;
  versionCount: string;
  createAt: string;
};
interface node {
  nodeName: string,
  nodeId: string;
  nodeType: string,
  status: string,
  updateAt: string,
}

interface port {
  id: number;
  key: number|string;
  value: number|string;
}
interface device {
  type: string;
  series: string;
  deviceNum: number;
  cpu: number;
  memory: number;
}
interface Foo {
  [key: string]: string;
}
const Add: React.FC = (props) => {
  const [form] = Form.useForm();

  const [publicImages, setPublicImages] = useState([]);
  const [envs, setEnvs] = useState<env[]>([]);
  const [nodes, setNodes] = useState<node[]>([]);
  const [models, setModels] = useState<model[]>([]);
  const [series, setSeries] = useState<device[]>([]);
  const [imageSelect, setImageSelect] = useState({
    containerImage: '',
    containerImageTag: '',
  });
  const [tabImage, setTabImage] = useState('public');
  const [ports, setPorts] = useState<port[]>([{key: '', value: '', id: Date.now()}])
  const [start, setStart] = useState('')

  // 操作环境变量
  const addEnv = () => {
    const envsNow = [...envs];
    envsNow.push({ key: '', value: '' });
    setEnvs(envsNow);
  }
  const deleteEnv = (index: number) => {
    const envsNow = [...envs];
    envsNow.splice(index, 1);
    setEnvs(envsNow);
  }
  const updateEnv = (key: string, value: string, index: number) => {
    const envsNow = [...envs];
    envsNow[index] = { key, value };
    console.log(envsNow);
    setEnvs(envsNow);
  }

  // 操作模型
  const getModel = (models: []) => {
    setModels(models);
  }

  // 提交，创建推理
  const create = (values:inference) => {
    console.log(start);
    console.log(models);
    console.log(nodes);
    console.log(imageSelect);
    const hasModel = models.length > 0;
    const hasNode = nodes.length > 0;
    const hasImage = imageSelect.containerImage;
    const hasPort = ports.length > 0;
    const hasInferPort = ports[0].key && ports[0].value
    console.log(hasModel)
    console.log(hasNode)
    console.log(hasImage)
    console.log(hasPort)
    console.log(hasInferPort)
    if (!(hasModel && hasImage && hasNode && hasPort && hasInferPort)) {
      !hasModel && message.error('请选择模型')
      !hasNode && message.error('请选择节点')
      !hasImage && message.error('请选择镜像')
      !hasInferPort && message.error('请选择输入推理端口');
      return;
    }
    const envsParams: Foo = {};
    envs.forEach(env => {
      envsParams[env.key] = env.value;
    })
    const nodeIds = nodes.map(node => node.nodeId);
    const portsParams = {
      infer: {},
      others: {}
    };
    ports.forEach((port, index) => {
      portsParams[!index ? 'infer' : 'others'][port.key] = port.value;
    });
    const params = {
      'name': values.name,
      'describe': values.describe,
      models: models.map(model => ({
        name: model.modelName,
        id: model.id,
        version: model.version,
        versionId: model.versionId,
      })),
      'envs': envsParams,
      containerImage: imageSelect.containerImage,
      containerImageTag: imageSelect.containerImageTag,
      containerRunCmd: values.containerRunCmd || '',
      containerRunParams: values.containerRunParams || '',
      containerRestart: start || 'always',
      nodeIds,
      containerPorts: portsParams,
      containerNetwork: 'host', // 暂时不做，传空
    };
    console.log(params);
    addInference(params).then(res => {
      if (res && res.code === 0) {
        history.push('/deploy-online/edge-inference');
      } else {
        message.error('创建失败');
      }
    })
  }

  useEffect(() => {
    // 先获取公共镜像，如果公共镜像没有，提示用户选择我的镜像
    getPublicImage().then(res => {
      if (res && res.code === 0) {
        // const images = res.data.items?.map((image: image) => image.imageName)
        // const images = res.data.items?.map((image: image) => image.imageName)
        setPublicImages(res.data.items);
      }
    });
  }, [])
  useEffect(() => {
    if(models.length && models[0].devices && Array.isArray(models[0].devices)){
      setSeries(models[0].devices.map(e=>e['series']));
    }
    setNodes([]);
  }, [models]);
  // useEffect(() => {
  //   models.length && getInference(models[0].id, models[0].versionId).then(res => {
  //     if (res && res.data) {
  //       const inference = res.data.modelVersionInference;
  //       if (inference && inference.edge) {
  //         const { devices } = res.data.modelVersionInference?.edge as { devices: device[]}
  //         const types = devices.map(i => i.type);
  //         getNodes().then(res => {
  //           if (res && res.data) {
  //             const { items } = res.data as { items: node[]};
  //             const itemsOnline = items.filter(i => i.status === 'online');
  //             if (!itemsOnline.length){
  //               message.error('暂无节点');
  //             } else{
  //               setNodes(itemsOnline);
  //             }
  //           }
  //         })
  //         console.log(devices);
  //         console.log(devices[0].type);
  //       } else {
  //         message.error({ content: '暂无模型对应节点类型'})
  //       }
  //     }
  //   })
  // }, [models])

  return (
    <PageContainer onBack={() => history.push('/deploy-online/edge-inference')}>
      {/* <Card> */}
        <Form
          form={form}
          {...FORM_LAYOUT}
          onFinish={(values)=>create(values)}
        >
          <Card>
            <Item
              label={trans('deployOnline.edgeInference.add.name')}
              labelAlign='left'
              name='name'
              initialValue={`default-${Math.ceil(Math.random()*1000)}`}
              rules={nameRule()}
            >
              <Input></Input>
            </Item>
            <Item
              label={trans('deployOnline.edgeInference.add.descrite')}
              labelAlign='left'
              name='describe'
            >
              <Input.TextArea
                autoSize={{minRows:3}}
                maxLength={200}
                showCount
                placeholder={trans('common.descriptionTip')}/>
            </Item>
          </Card>
          <Card style={{marginTop: '10px'}}>
            <InfoTitle title='deployOnline.edgeInference.add.selectModel'></InfoTitle>
            <Item label={trans('deployOnline.edgeInference.add.model')} labelAlign='left' required>
              <SelectModel getModel={getModel}></SelectModel>
            </Item>
            <Item
              label={trans('deployOnline.edgeInference.add.env')}
              tooltip={trans('deployOnline.edgeInference.add.envTip')}
              labelAlign='left'
            >
              <AddEnv envs={envs} setEnvs={setEnvs}></AddEnv>
            </Item>
          </Card>

          <Card style={{marginTop: '10px'}}>
            <InfoTitle title='deployOnline.edgeInference.add.containerConfiguration'></InfoTitle>
            <Item
              label={trans('deployOnline.edgeInference.add.image')}
              required
              labelAlign='left'
            >
              <SelectImage
                setTabImage={setTabImage}
                tabImage={tabImage}
                models={models}
                publicImages={publicImages}
                imageSelect={imageSelect}
                setImageSelect={setImageSelect} />
            </Item>
          </Card>

          <Card style={{marginTop: '10px'}}>
            <InfoTitle title='deployOnline.edgeInference.add.selectNode'></InfoTitle>
            <SelectNode
              nodes={nodes}
              setNodes={setNodes}
              models={models}
              series={series}
            ></SelectNode>
          </Card>

          <Card style={{marginTop: '10px'}}>
            <InfoTitle title='deployOnline.edgeInference.advancedConfiguration'></InfoTitle>
            <Item labelAlign='left' wrapperCol={{ offset: 4, span: 16 }}>
              <AdvancedConfiguration tabImage={tabImage} setStart={setStart} start={start}></AdvancedConfiguration>
            </Item>
          </Card>

          <Card style={{marginTop: '10px'}}>
            <InfoTitle title='deployOnline.edgeInference.accessConfiguration'></InfoTitle>
            {/* <Item
              label={trans('deployOnline.edgeInference.add.netType')}
              name='netType'
              required
              initialValue={trans('deployOnline.edgeInference.add.hostNetwork')}>
              <Group
                options={optionsNet}
                optionType='button'
                buttonStyle='solid'></Group>
            </Item> */}
            <PortMapping setPorts={setPorts}  ports={ports}></PortMapping>
          </Card>

          <Button style={{marginTop: '20px'}} htmlType='submit' type='primary'>{trans('common.create')}</Button>
        </Form>
      {/* </Card> */}
    </PageContainer>
  )
}

export default Add;
